package rabbitMQ.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitMQ.common.Common;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerDemo {

    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost(Common.HOST);//ip
        factory.setPort(Common.PORT);//端口号
        factory.setVirtualHost(Common.VIRTUALHOST);//虚拟机名称
        factory.setUsername(Common.USERNAME);//用户名
        factory.setPassword(Common.PASSWORD);//密码
        //3. 创建连接connection
        Connection connection = factory.newConnection();

        //创建channel
        Channel channel = connection.createChannel();

        //声明队列
        //如果没有一个这样的队列, 会自动创建, 如果有, 则不创建
        channel.queueDeclare(Common.SIMPLE_QUEUE, true, false, false, null);

        for (int i = 0; i < 10; i++) {
            //发送消息
            String msg = Common.SIMPLE_MSG + i;
            channel.basicPublish("", Common.SIMPLE_QUEUE, null, msg.getBytes(StandardCharsets.UTF_8));
        }

        //释放资源
        channel.close();
        connection.close();
    }
}
